package com.mao.controller;


import com.mao.common.BaseContext;
import com.mao.common.Result;
import com.mao.entity.AddressBook;
import com.mao.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/addressBook")
public class AddressBookController {

    @Autowired
    private AddressBookService addressBookService;

    /**
     * 新增地址簿
     * @param addressBook
     * @return
     */
    @PostMapping
    public Result<String> save(@RequestBody AddressBook addressBook){
        addressBook.setUserId(BaseContext.getCurrentId());
        boolean success = addressBookService.save(addressBook);
        if (!success){
            return Result.error("保存失败");
        }
        return Result.success("保存成功");
    }

    /**
     * 查询所有的地址簿
     * @return
     */
    @GetMapping("/list")
    public Result<List<AddressBook>> list(AddressBook addressBook){
        List<AddressBook> addressBookList = addressBookService.listAddressBook(addressBook);
        if (addressBookList.isEmpty()){
            return Result.error("你没有添加地址哦");
        }
        return Result.success(addressBookList);
    }

    /**
     * 更新默认地址簿
     * @param addressBook
     * @return
     */
    @PutMapping("/default")
    @Transactional
    public Result<AddressBook> update_default(@RequestBody AddressBook addressBook){
        addressBookService.update_Default(addressBook);
        return Result.success(addressBook);
    }

    /**
     * 获取默认地址簿
     * @return
     */
    @GetMapping("/default")
    public Result<AddressBook> get_Default(){
        AddressBook addressBook = addressBookService.get_Default();
        return Result.success(addressBook);
    }

    /**
     * 查询地址簿
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<AddressBook> get(@PathVariable String id){
        AddressBook addressBook = addressBookService.getById(id);
        return Result.success(addressBook);
    }

    /**
     * 修改地址簿
     * @param addressBook
     * @return
     */
    @PutMapping
    public Result<String> update(@RequestBody AddressBook addressBook){
        addressBookService.updateById(addressBook);
        return Result.success("修改成功");
    }

    /**
     * 删除地址簿
     * @param ids
     * @return
     */
    @DeleteMapping
    public Result<String> remove(@RequestParam("ids") Long ids){
        addressBookService.removeById(ids);
        return Result.success("删除成功");
    }


}
